package com.example.demo.mapper;

import com.example.demo.model.UserCheckIn;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Mapper
public interface UserCheckInMapper {

    @Select("SELECT * FROM user_check_in WHERE user_id = #{userId} AND check_in_date = #{date}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "checkInDate", column = "check_in_date"),
            @Result(property = "pointsEarned", column = "points_earned")
    })
    UserCheckIn findByUserIdAndCheckInDate(@Param("userId") Long userId, @Param("date") LocalDate date);

    @Select("SELECT EXISTS (SELECT 1 FROM user_check_in WHERE user_id = #{userId} AND check_in_date = #{date})")
    boolean existsByUserIdAndCheckInDate(@Param("userId") Long userId, @Param("date") LocalDate date);

    @Select("SELECT * FROM user_check_in WHERE user_id = #{userId} ORDER BY check_in_date DESC LIMIT 1")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "checkInDate", column = "check_in_date"),
            @Result(property = "pointsEarned", column = "points_earned")
    })
    UserCheckIn findFirstByUserIdOrderByCheckInDateDesc(@Param("userId") Long userId);

    @Select("SELECT check_in_date FROM user_check_in WHERE user_id = #{userId} AND check_in_date >= #{startDate}")
    List<LocalDate> findCheckInDatesAfter(@Param("userId") Long userId, @Param("startDate") LocalDate startDate);

    @Select("SELECT COUNT(*) FROM user_check_in WHERE user_id = #{userId} AND check_in_date = #{date}")
    int countByUserIdAndDate(@Param("userId") Long userId, @Param("date") LocalDate date);

    @Insert("INSERT INTO user_check_in (user_id, check_in_date, points_earned) VALUES (#{userId}, #{checkInDate}, #{pointsEarned})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertCheckIn(UserCheckIn checkIn);
}